package com.vueperson.vueperson.services.handle;


import com.vueperson.vueperson.dao.RoleJPA02;
import com.vueperson.vueperson.dao.UserJPA02;
import com.vueperson.vueperson.entity.Role02;
import com.vueperson.vueperson.entity.User02;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class Role01_03 extends Role01_01 {
    @Autowired
    RoleJPA02 roleJPA;

    @Autowired
    Role02 role;
    @Autowired
    User02 user;
    @Autowired
    UserJPA02 userJPA;

    @Qualifier("role02_2")
    @Autowired
    Role2 roleIf;

    @Override
    public void saveRole(String name, String nameZh) {
        int i=roleJPA.findByNameOrNameZh(name,nameZh).size();
        if (i!=0){
            System.out.println("已有用户名");
            return;
        }
        role.setNameZh(nameZh);
        role.setName(name);
        roleJPA.save(role);
    }

    public void saveUser(String username, String password, List<String> roleNames) {
        if (roleIf.haveUser(username)) {
            return;
        }
       if (roleNames.size()==0){return;};
        for (String roleName:roleNames){
            if (!roleIf.haveRole(roleName)) {
                return;
            }
        }


        //创建用户
        user.setUsername(username);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encodePassword=bCryptPasswordEncoder.encode(password);
        user.setPassword(encodePassword);

        //创建角色
       List<Role02> role02s =new ArrayList<>();
        for (String roleName:roleNames){
            role02s.add(roleJPA.findByName(roleName).get(0));
        }

//        role=roleJPA.findByName(roleName).get(0);

        //关联
        for (Role02 role02:role02s){
            user.getRole02s().add(role02);
        }


        //保存
        userJPA.saveAndFlush(user);

        System.out.println("保存成功");
    }


}
